import re


class CountWords(object):
    def __init__(self, file_name):
        self.file_name = file_name
        self.words = {}

    def count_word(self):
        with open(self.file_name, 'r') as f:
            for line in f.readlines():
                print('line', line)
                words = [x.lower() for x in re.findall("\w+", line)]
                print('words', words)
                self.set_count(words)

    def set_count(self, words):
        for key in words:
            self.words[key] = self.words.get(key, 0) + 1
            # if self.words.get(key):
            #     self.words[key] = self.words[key] + 1
            # else:
            #     self.words[key] = 1
        print('self.words', self.words)

    def top_num(self, count):
        words_sorted = sorted(self.words.items(), key=lambda it: it[1], reverse=True)[:count]
        print('words_sorted', words_sorted)
        return words_sorted


if __name__ == '__main__':
    file_name = './2.2.2_test.txt'
    number = 6
    countWords = CountWords(file_name)
    countWords.count_word()
    top_numbers = countWords.top_num(number)
    print(file_name, '出现次数最多的%词', top_numbers)
    for item in top_numbers:
        print('%s出现: %d 次' % (item[0], item[1]))
